package cn.edu.scau.cmi.wubaorun.hibernate.dao;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import cn.edu.scau.cmi.wubaorun.hibernate.domain.Teacher;

public class TeacherDAO {

	public void save(Teacher teacher) {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		openSession.beginTransaction();
		openSession.save(teacher);
		openSession.getTransaction().commit();
		openSession.close();
		buildSessionFactory.close();
	}

	public void delete(Teacher teacher) {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		openSession.beginTransaction();
		openSession.delete(teacher);
		openSession.getTransaction().commit();
		openSession.close();
		buildSessionFactory.close();

	}

	public void update(Teacher teacher) {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		openSession.beginTransaction();
		openSession.update(teacher);
		openSession.getTransaction().commit();
		openSession.close();
		buildSessionFactory.close();
	}

	public Teacher get(long id) {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		Teacher teacher = (Teacher) openSession.get("cn.edu.scau.cmi.wubaorun.hibernate.domain.Teacher", id);
		openSession.close();
		buildSessionFactory.close();
		return teacher;
	}

	public List<Teacher> list() {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		Query<Teacher> query = openSession.createSQLQuery("select * from teacher").addEntity(Teacher.class);
		List<Teacher> list = query.list();
		openSession.close();
		buildSessionFactory.close();
		return list;
	}
}